package cn.myframe.task.quartz;

import java.io.File;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import org.apache.commons.lang.time.DateFormatUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import cn.myframe.entity.sys.SysParameterEntity;
import cn.myframe.service.sys.SysParameterService;
import cn.myframe.utils.AESCode;
import cn.myframe.utils.DateUtils;
import cn.myframe.utils.FileUtils;

@Component("DbBackScheduler")
public class DbBackScheduler {

	private static Logger log = LoggerFactory.getLogger(DbBackScheduler.class);
	
	@Autowired
	private SysParameterService sysParameterService;
	
	@Value("${spring.datasource.url:#{null}}")
	private String dbUrl;	
	
    @Value("${spring.datasource.password}")
    private String dbPassword="";
    
	@Value("${spring.datasource.username}")
    private String username="";
	 /**
     * 数据库定时备份
     */
    //@Scheduled(cron="${schedule.backup.DBcron}") 
    public void DBback(){
    	//mysqldump -u root --password=test123 --database nias > /opt/backup/nias.sql;
    	System.out.println("========================数据库定时备份开始。。。=========================");
    	SysParameterEntity uploadParameter = sysParameterService.queryByKey("BACK_PATH");
    	String day = sysParameterService.queryByKey("STAY_DAY").getParamValue().toString();
    	String backPath=uploadParameter.getParamValue();
    	if(!backPath.endsWith(File.separator)){
    		backPath += File.separator;
    	}
    	File file = new File(backPath);
    	if(!file.exists()){
    		file.mkdirs();
    	}
    	//获取数据库名
    	int start = dbUrl.lastIndexOf("/");
		int startIndex =  dbUrl.indexOf("/");
		int end = dbUrl.indexOf("?");	
		int endIndex = dbUrl.lastIndexOf(":");
		String dbName = dbUrl.substring(start+1,end);
		String host = dbUrl.substring(startIndex+2,endIndex);
		String password = AESCode.decrypt(dbPassword);
		if(!backPath.startsWith("/")){
			backPath = "/" + backPath;
		}
		if(!backPath.endsWith("/")){
			backPath  = backPath + "/";
		}
		try {
			backup(host,username, password,dbName, backPath,day);
		} catch (Exception e) {
			e.printStackTrace();
		}
		
    }
	private void backup(String host, String username, String password, String dbName, String backPath,String  day) {
		try {
		    String dateStr = DateUtils.format(new Date(), "yyyyMMdd");
		    String date = DateUtils.format(new Date(), "yyyyMMddHHmmss");
		    String delBfPath = backPath;
		    backPath = backPath + File.separator + dateStr;
			File file = new File(backPath);
			if(!file.exists()){
				file.mkdirs();
			}
			Runtime rt = Runtime.getRuntime();
			String cmd = "mysqldump -h "+host+" -u "+username+" -p"+password+" -R -c --set-charset=utf8 "+dbName +" | gzip > "+ backPath+ File.separator+date +".sql.gz";
			String[] cmds=new String[]{"/bin/sh","-c",cmd};
			rt.exec(cmds);
			delteDbBf(delBfPath,day);
	 } catch (Exception e) {
         e.printStackTrace();
     }
	}
	private void delteDbBf(String delBfPath, String day) {
		try {
	    	String deleteDate = null; 
	    	Date deleteTime  =null;
	        Date date=new Date();  
	        Calendar calendar = Calendar.getInstance();  
	        calendar.setTime(date);
	        calendar.add(Calendar.DAY_OF_MONTH, -Integer.valueOf(day));
	        deleteDate = DateFormatUtils.format(calendar.getTime(), "yyyyMMdd");
	        deleteTime= org.apache.commons.lang.time.DateUtils.parseDate(deleteDate, new String[]{"yyyyMMdd"});
			File file = new File(delBfPath);
			File[] files = file.listFiles();
			for(int i=0;i<files.length;i++){
				 long time = files[i].lastModified();//返回文件最后修改时间，是以个long型毫秒数
				 String ctime = new SimpleDateFormat("yyyyMMdd").format(new Date(time));
				 Date fileTime = org.apache.commons.lang.time.DateUtils.parseDate(ctime, new String[]{"yyyyMMdd"});
				 if(fileTime.getTime()<deleteTime.getTime()){
					 FileUtils.deleteDir(files[i]);
				 }
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
